var viewer = new Cesium.Viewer('cesiumContainer',{
	projectionPicker : true,
	selectionIndicator : false,
    infoBox : false
});
var position = Cesium.Cartesian3.fromDegrees(114.17976,22.30403, 0);
var heading = Cesium.Math.toRadians(0);
var pitch = 0;
var roll = 0;
var hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
var orientation = Cesium.Transforms.headingPitchRollQuaternion(position, hpr);
var model = viewer.entities.add({
	name : '8',
	position : position,
	orientation : orientation,
	model : {
		uri : 'data/m345/m345.gltf'
	}
})
viewer.zoomTo(model);
var centerLatitude = 22.30403*Math.PI/180;
var centerLongitude = 114.17976*Math.PI/180;
var dragonScale = 1.0;
var dragonOffset = 0;//dragonHeight / 2.0 * dragonScale;
var dragonCartesian = Cesium.Cartesian3.fromRadians(centerLongitude, centerLatitude, dragonOffset);
var scaleMatrix = Cesium.Matrix4.fromUniformScale(dragonScale);
var wgs84Matrix = Cesium.Transforms.headingPitchRollToFixedFrame(dragonCartesian, new Cesium.HeadingPitchRoll(0, 0, 0));
var dragonMatrix = Cesium.Matrix4.multiply(wgs84Matrix, scaleMatrix, new Cesium.Matrix4());
// var dragonTransform = new Array(16);
// Cesium.Matrix4.pack(dragonMatrix, dragonTransform);
var invMatrix = new Cesium.Matrix4();
Cesium.Matrix4.inverse(dragonMatrix,invMatrix);

var pathfinder = new THREE.Pathfinding();
var jsonLoader = new THREE.JSONLoader();
var player, target;
var playerNavMeshGroup;
var calculatedPath = null;
var pathDataSource = new Cesium.CzmlDataSource('path');
jsonLoader.load( 'data/m345/m345nav.js', function( geometry, materials ) {
	var zoneNodes = THREE.Pathfinding.createZone(geometry);
	pathfinder.setZoneData('level', zoneNodes);
	player = new THREE.Mesh();
	player.position.set(15.03948679822497,12.980388324707747,10.243011781247333);
	target = new THREE.Mesh();
	target.position.copy(player.position);
	// Set the player's navigation mesh group
	playerNavMeshGroup = pathfinder.getGroup('level', player.position);
	console.log('nav loaded');
}, null);

handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
handler.setInputAction(function(movement) {
	var scene = viewer.scene;
	if (scene.mode !== Cesium.SceneMode.MORPHING) {
		var pickedObject = scene.pick(movement.position);
		if (scene.pickPositionSupported && Cesium.defined(pickedObject) && pickedObject.id) {
			var cartesian = viewer.scene.pickPosition(movement.position);
			if (Cesium.defined(cartesian)) {
				var positionLC = positionWC2LC(cartesian,invMatrix);
				// positionLC.y+=1;
				target.position.copy(positionLC);
				console.log(player.position);
				console.log(target.position);
				// player.position.y+=1;
				calculatedPath = pathfinder.findPath(player.position, target.position, 'level', playerNavMeshGroup);
				console.log(pathfinder);
				if (calculatedPath && calculatedPath.length) {
					viewer.dataSources.remove(pathDataSource,false);
					pathDataSource.entities.removeAll();
					var startcoord = positionLC2WC(player.position,dragonMatrix);
					var endcoord = positionLC2WC(target.position,dragonMatrix);
					// Draw debug lines
					var positions = [];
					positions.push(startcoord);
					for (var i = 0; i < calculatedPath.length; i++) {
						var lineposition = positionLC2WC(calculatedPath[i],dragonMatrix);
						positions.push(lineposition);
					}
					pathDataSource.entities.add({
						polyline : {
							positions : positions,
							width : 20,
							material : new Cesium.PolylineGlowMaterialProperty({
								glowPower : 0.2,
								color : Cesium.Color.BLUE
							})
						}
					});

					pathDataSource.entities.add({
						id:'start',
						name:'起点',
						position:startcoord,
						point : {
							pixelSize : 10,
							color : Cesium.Color.RED
						}
					});
					pathDataSource.entities.add({
						id:'end',
						name:'终点',
						position:endcoord,
						point : {
							pixelSize : 10,
							color : Cesium.Color.GREEN
						}
					});
					viewer.dataSources.add(pathDataSource);
					player.position.copy(target.position);
				}
			}
		}
	}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);

function positionLC2WC(positionLC,matrix){
	var positionWC = new Cesium.Cartesian3();
	var lc = new Cesium.Cartesian3(positionLC.x,-positionLC.z,positionLC.y);
    Cesium.Matrix4.multiplyByPoint(matrix, lc, positionWC);
	return positionWC;
}
function positionWC2LC(positionWC,invm){
	var lc = new Cesium.Cartesian3();
    Cesium.Matrix4.multiplyByPoint(invm, positionWC, lc);
	var positionLC = new THREE.Vector3(lc.x,lc.z,-lc.y);
	return positionLC;
}